package com.eco.fanliapp.job.hdkitemjob;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.eco.fanliapp.common.constant.ApiEnum;
import com.eco.fanliapp.dao.AppGoodsMapper;
import com.eco.fanliapp.entity.*;
import com.eco.fanliapp.service.*;
import com.eco.fanliapp.utils.*;
import com.eco.fanliapp.vo.HaoDanKuItemInfo;
import org.quartz.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.Serializable;
import java.math.BigDecimal;
import java.util.*;


@DisallowConcurrentExecution
@PersistJobDataAfterExecution
public class HDKItemsSaveOrUpdateTask implements Job, Serializable {
    private static final Logger log = LoggerFactory.getLogger(getFullHDKItemsTask.class);
    @Autowired
    private IJobOrderInfoGetService jobOrderInfoGetService;
    @Autowired
    private IAppGoodsService appGoodsService;

    @Autowired
    private AppGoodsMapper appGoodsMapper;


    public HDKItemsSaveOrUpdateTask() {
    }

    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {

        //取得job详情
        JobDetail jobDetail = context.getJobDetail();

        JobDataMap dataMap = jobDetail.getJobDataMap();

        int executeCount = 0;
        if (dataMap.containsKey("runCount")) {
            executeCount = dataMap.getInt("runCount");
        }

        // 增量计数并将其存储回 JobDataMap，这样可以适当保持工作状态
        executeCount++;
        dataMap.put("runCount", executeCount);

        long beginTime = System.currentTimeMillis();
        log.info("***************************************开始执好单库商品列表入库定时任务-getFullHDKItemsTask：executeCount=" + executeCount + "--beginTime=" + beginTime);

        CountLauncher countLauncher = new CountLauncher(10);
        jobOrderInfoGetService.setCountLauncher(countLauncher);
        long startMillions = System.currentTimeMillis();
        long back = 500;
        int intArray[] = {10, 11, 4, 1, 9, 3, 2, 6, 12, 15, 5, 7, 8, 13, 16, 17};
        for (int y = 0; y < intArray.length; y++) {
            int n = 0;
            long min = 1;
            appGoodsMapper.updateGoods("10000", null, intArray[y]);
            while (true) {

                Map<String, Object> data = new HashMap<String, Object>();
                data.put("nav", "3");
                data.put("back", back);
                data.put("min_id", min);
                data.put("sort", 11);
                data.put("cid", intArray[y]);

                try {
                    String str = ApiUtils.getData(ApiEnum.ITEMLIST, data);

//                log.info("获取好单库商品列表数据{}", str);
                    JSONObject object = JSONObject.parseObject(str);
                    AppGoods response = JsonUtils.getJsonToBean(object.toJSONString(), AppGoods.class);
                    if (response != null && response.getCode() == 1) {  //code等于1代表请求成功
                        JSONArray array = JSONArray.parseArray(object.getJSONArray("data").toJSONString());
                        List<HaoDanKuItemInfo.DataBean> bean = JsonUtils.getJsonToList(array.toJSONString(), HaoDanKuItemInfo.DataBean.class);
                        if (bean == null || bean.size() <= 0) {
                            break;
                        }
                        List<AppGoods> updateAppGoodsList = new ArrayList<>();
                        List<AppGoods> addAppGoodsList = new ArrayList<>();
                        for (HaoDanKuItemInfo.DataBean haoDanKuItemInfo : bean) {
                            AppGoods dataBean = HDKUtils.getAppGoodsFromHDK(haoDanKuItemInfo);
                            String tkMoney_ =
                                    BigDecimalUtils.FanliMoney(dataBean.getTkrates(),
                                            new BigDecimal(dataBean.getItemendprice())).toString();
                            dataBean.setTkmoney(tkMoney_);
                            dataBean.setFanliUpdateTime((System.currentTimeMillis()) + "");
                            dataBean.setItemType(1);
//
//                            //判断是否最终金额小于0
                            BigDecimal itemendprice = new BigDecimal(dataBean.getItemendprice() == null ? 0d : dataBean.getItemendprice());
                            BigDecimal tkMoney = new BigDecimal(dataBean.getTkmoney() == null ? "0" : dataBean.getTkmoney());
                            if ((itemendprice.subtract(tkMoney)).compareTo(new BigDecimal(0)) < 0) {
                                continue;
                            }
                            dataBean.setCreateTime(DateUtils.getNowTimestamp());
                            dataBean.setUpdateTime(DateUtils.getNowTimestamp());
                            dataBean.setAddUserId(-115);

                            AppGoods appGoods = appGoodsMapper.findAppGoodsByItemId(dataBean.getItemid());
                            if (appGoods != null) {
                                if (appGoods.getItemTop() == 1 && appGoods.getDeleted() == 0) {
                                    if (appGoods.getRecommend() != 1) {
                                        dataBean.setSort(n++);
                                    }
                                    updateAppGoodsList.add(dataBean);
                                } else {
                                    continue;
                                }
                            } else {
                                dataBean.setSort(n++);
                                addAppGoodsList.add(dataBean);
                            }
                        }

                        if (addAppGoodsList.size() > 0) {
                            try {
                                boolean flag = appGoodsService.saveBatch(addAppGoodsList);
                                if (flag) {
                                    log.info("商品拉取API   入库商品新增成功 size=" + addAppGoodsList.size());
                                } else {
                                    log.info("商品拉取API   入库商品新增失败" + addAppGoodsList.toString());
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }

                        if (updateAppGoodsList.size() > 0) {
                            for (AppGoods goods : updateAppGoodsList) {
                                try {
                                    int i = appGoodsService.updateBatchByItemId(goods);
                                    if (i > 0) {
                                        log.info("商品拉取API   入库商品更新成功 数据size={} ", updateAppGoodsList.size());
                                    } else {
                                        log.info("商品拉取API   入库商品更新失败 数据={} ", updateAppGoodsList.toString());
                                    }
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                        }

                    } else {
                        log.info("商品拉取API   请求失败{}", response.getMsg());
                        break;
                    }
                    if (response.getMinId() != null) {
                        min = response.getMinId();
                    } else {
                        break;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    log.error("商品拉取API   0 0/3 * * * ? 失败 耗时" + (System.currentTimeMillis() - startMillions) + "   错误=" + e.getMessage());
                    break;
                }
            }
        }
        long endTime = System.currentTimeMillis();
        log.info("***************************************结束好单库商品列表入库定时任务-getFullHDKItemsTask：executeCount=" + executeCount + "--endTime=" + endTime + "--耗时=" + (endTime - beginTime));

    }
}

